
#ifndef LINCONTROL_H
#define LINCONTROL_H

#include"glheader.h"

class LinControl
{
  private:
  float m_x1;
  float m_y1;
  float m_x2;
  float m_y2;
  int m_xmax;
  int m_ymax;
  int m_drag;
  bool HitPoint(float px,float py, float x, float y)
  {
    float norm2 = (px-x)*(px-x) + (py-y)*(py-y);
    return norm2 < ((float)m_xmax/10.0)*((float)m_xmax/10.0);
  }
  public:
  LinControl(int xmax, int ymax): m_x1(xmax/3.0), m_x2(2*xmax/3.0), m_y1(ymax/3.0), m_y2(2*ymax/3.0), m_xmax(xmax),m_ymax(ymax),m_drag(0){};
  void Draw ()
  {
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0, m_xmax, 0, m_ymax);
    glColor3f(0.0,0.0,0.0);
    glBegin(GL_LINE_STRIP);
      glVertex2f(0.0,0.0);
      glVertex2f(m_x1,m_y1);
      glVertex2f(m_x2,m_y2);
      glVertex2f(m_xmax,m_ymax);
    glEnd();
    glPointSize(8.0);
    glBegin(GL_POINTS);
      glVertex2f(m_x1,m_y1);
      glVertex2f(m_x2,m_y2);
    glEnd();
  }
  bool MouseMotion (int x, int y){
    if(x>=0 && x<=m_xmax && y>=0 && y<=m_ymax){
      if(m_drag==1){  
        m_x1 = (float)x;
        m_y1 = (float)y;
        if(m_x1>m_x2)
          m_x2=m_x1;
        //if(m_y1>m_y2)
          //m_y2=m_y1;
        return true;
      }
      else if(m_drag==2){
        m_x2 = (float)x;
        m_y2 = (float)y;
        if(m_x2<m_x1)
          m_x1=m_x2;
        return true;
      }
    }
    return false;
  };
  void MouseLeftDown (int x, int y)
  {
    if(HitPoint(m_x1,m_y1,(float)x,(float)y)){
      m_drag=1;
      return; 
    }
    if(HitPoint(m_x2,m_y2,(float)x,(float)y))
      m_drag=2;
  };
  void MouseLeftUp (int x, int y)
  {
    m_drag=0;
  };
  void GetXs(int * x1, int * x2){
    *x1 = (int) m_x1;
    *x2 = (int) m_x2;
  }
  void GetEq(float* eq){
    float nx1 = m_x1/m_xmax;
    float ny1 = m_y1/m_ymax;
    float nx2 = m_x2/m_xmax;
    float ny2 = m_y2/m_ymax;
    eq[0] = ny1/nx1;
    eq[1] = 0;
    eq[2] = (ny2-ny1)/(nx1!=nx2?(nx2-nx1):1);
    eq[3] = ny2 - eq[2]*nx2;
    eq[4] = (1-ny2)/(1!=nx2?(1-nx2):1);
    eq[5] = ny2 - eq[4]*nx2;
  }
};

#endif
